package com.xs.aifitnessagent.chatmemory;

import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 基于 Redis 的对话记忆
 *
 * @author lambor
 */
@Component
public class RedisChatMemory implements ChatMemory {

    private final RedisTemplate<String, Message> messageRedisTemplate;

    private static final String REDIS_KEY_PREFIX ="CHAT_MEMORY";

    public RedisChatMemory(RedisTemplate<String, Message> messageRedisTemplate) {
        this.messageRedisTemplate = messageRedisTemplate;

    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        // 将新消息追加到列表尾部
        messageRedisTemplate.opsForList().rightPushAll(getKey(conversationId), messages);
    }

    @Override
    public List<Message> get(String conversationId) {
        ListOperations<String, Message> ops = messageRedisTemplate.opsForList();
        String key = getKey(conversationId);
        return Objects.requireNonNull(ops.range(key, 0, -1));
    }

    @Override
    public void clear(String conversationId) {
        messageRedisTemplate.delete(conversationId);
    }

    private String getKey(String conversationId) {
        return REDIS_KEY_PREFIX +":"+conversationId;
    }

}